/**
 * @author {kidy lv}
 */
var QS_HomepageCalendars=function(cb){
    this.containerId = null;
	this.callback={};
	$.extend(true,this.callback,cb);
    this.container = null;
	this.firstTag=true;
	this.homePageHeadInfo={
		"0":[{
				col:[
						{
							header:'Company'
						},
						{
							dataIndex: 'company',
							dataType: 'string',
							className: 'qs-calendars-right'
						}
				   ],
				className:"qs-calendars-main"
			},
			{
				col:[
						{ 
							header:'Wall St EPS EST'
						},{
							dataIndex: 'wallStEPSEst',
							dataType: 'string',
							className: "qs-calendars-right"
						}
					],
				className:"qs-calendars-secondary"
			},
			{
				col:[
						{
							header: 'Actual EPS'
						},
						{
							dataIndex: 'actualEPS',
							dataType: 'string',
							className: "qs-calendars-right"
						}
					],
				className:"qs-calendars-secondary"
			},
			{
				col:[//createDate
					{
						header: 'CurrrentDate'
					},
					{
						dataIndex: 'createDate',
						root:true,
						dataType: 'date',
						dataFormat:'engMonth',
						className: 'qs-calendars-right'
					}
				],
				className:"qs-calendars-row"
			}
			],
		"4":[
			{
				col:[
					{
						dataIndex: 'release',
						dataType: 'string',
						renderer: function(txt,obj){
							if(obj.resourceId&&$.trim(obj.resourceId)!=""){
								return '<a class="econ_cal_link" href="javascript:void(0)" resourceId="'+obj.resourceId+'">'+txt+'</a>';
							}else{
								return txt;
							}
						}
					},
					{
						dataIndex: 'date',
						dataType: 'date',
						className: 'qs-calendars-right',
						dataFormat: 'engMonth'
					}
				],
                className:"qs-calendars-main"
            },{
                col:[
					{ 
						header:'Consensus'
					},
					{
						dataIndex: 'consensusEstimate',
						dataType: 'string',
						className: 'qs-calendars-right',
						renderer: function(txt){return txt==''?'--':txt;}
					}
				],
                className:"qs-calendars-secondary"
            },{
                col:[
					{
						header: 'Actual'
					}, 
					{
						dataIndex: 'afterReleaseActual',
						dataType: 'string',
						className: 'qs-calendars-right',
						renderer: function(txt){
							return txt == '' ? '--' : txt;
						}
					}
				],
                className:"qs-calendars-row"
           }
        ],
		"5":[{
				col:[
						{
							header:'Event'
						},
						{
							dataIndex: 'event',
							dataType: 'string',
							subLen:10,
							renderer:function(txt,obj){
								var url=obj.url;
								return url!=''?'<a class="econ_cal_link" href="'+url+'" title="'+obj.event+'" target="blank">'+txt+'</a>':'<span title="'+obj.event+'" >'+txt+'</span>';
							},
							className: 'qs-calendars-right'
						}
				   ],
				className:"qs-calendars-main"
			},
			{
				col:[
						{ 
							header:'Start Date'
						},{
							dataIndex: 'dateTime',
							dataType: 'date',
							dataFormat: 'date',
							className: "qs-calendars-right"
						}
					],
				className:"qs-calendars-secondary"
			},
			{
				col:[
						{ 
							header:'End Date'
						},{
							dataIndex: 'endDate',
							dataType: 'date',
							dataFormat: 'date',
							className: "qs-calendars-right"
						}
					],
				className:"qs-calendars-row"
			}
		]
	};
	this.staticValue={
		minWidth:230,
		tabMenuHeight:30
	};
    this.profile={
		top:5,
		fixHeight:true,
		isAPI:true
	};
    this.id = null;
    this.el = null;
    this.dataEl=null;
    this.html=null;
    this.currentTab=null;
    this.tabMenu=null;
    this.dataScrollPN =null;
    this.serviceCode=typeof QSPC!='undefined'?(QSPC.checkPermission(2.16)?'TRADERCAL':QSPC.checkPermission(2.15)?'INPLAYCAL':'CORECAL'):serviceCode||"CORECAL";
};
QS_HomepageCalendars.prototype=$.extend(false,{
		showTab:true,
		showMore:true,
		viewMoreText:"View all",
		lastActiveTabId:4,
		homePageMenuData:[
			{
				txt: "Economic",
				id: 4,
				closable: false
			},
			{
				txt: "Earnings",
				id: 0,
				closable: false
			},
			{
				txt: "Events",
				id: 5,
				closable: false
			}
		]
	},typeof QSAPI_calendar!='undefined'?QSAPI_calendar:{},{
    init:function(containerId,profile,sid){
        this.containerId=containerId;
        this.container = $('#'+containerId);    
        this.id=sid;
        $.extend(this.profile,profile);
		if(profile.lastActiveTabId){
            this.lastActiveTabId=profile.lastActiveTabId;
        }
        this.html='<div class="rtq-calendar rtq-homepagecalendar">'+(typeof QSAPI_calendar!='undefined'?'<div class="qs-calendars-loading"><img src="common/loading.gif" /></div>':'')+'<div class="hd"><div class="tabmenu"></div></div><div class="bd"><div class="data"></div></div></div>'
        this.el=$(this.html);
		if (typeof QSAPI_calendar != 'undefined') {
			this.loadingEl = this.el.find(".qs-calendars-loading");
		}
        this.el.appendTo(this.container);
        this.dataEl=this.el.find('div.data');
        if (this.profile.fixHeight) {
            this.dataScrollPN = new Util.ScrollPanel($('div.data', this.el), {delayRun:false}, {
                onScroll: function(sl,st){
                }
            });
        }
        this.createMenu();  
    },
	_bindMoreEvent:function(){
		var moreEl=this.dataEl.find('.qs-calendars-more'),self=this;
		moreEl.unbind('click.eCalendar').bind('click.eCalendar',function(e){
			e.stopPropagation();
			if (typeof self.callback.onClick == 'function') {
				self.callback.onClick({
					component: "homepagecalendars",
					url: self._getCalendarsURL()
				});
			}
			else {
				self.openCalendars();
			}
		});
	},
    createMenu:function(){
        var self=this;
		if (this.showTab) {
			this.tabMenu = new Util.TabMenu($('.tabmenu', this.el)[0], this.homePageMenuData, {
				onActive: function(tab){
					self.currentTab = tab;
					self.createPage(tab.id);
				}
			}, {
				width: 100,
				autoResize: false,
				autoFixtoText: true,
				tabsList: false,
				activeTabId: self.lastActiveTabId,
				isExcuteCallbackAtInit: true
			});
		}else{
            self.createPage(this.lastActiveTabId);
		}
    },
	_addDate:function(y,m,d,n){//n can be positive or negative
        var d = new Date(y,m-1,d);
        d.setDate(d.getDate()+n);
        return d;
    },
    createPage:function(type){
        var self=this,
            date=new Date(),
            week=date.getDay(),
            year=date.getFullYear(),
            month=(date.getMonth()+1)<10?"0"+(date.getMonth()+1):(date.getMonth()+1),
            day=date.getDate()<10?"0"+date.getDate():date.getDate();        
        self.showLoading(true);
        if(week==0){
            date=this._addDate(year,month,day,-2);
        }if(week==6){
            date=this._addDate(year,month,day,-1);
        }
        var rtqDate=self._formatDate(date,"yyyy-mm-dd");
		DBHelper.getCalendar(type+'', rtqDate,this.serviceCode, function(o){
			if (o != null && $.trim(o) != '') {
				data= $.evalJSON(o);
			}
			if(self.currentTab&&self.currentTab.id!=type){
				return true;
			}
			self.dataEl[0].innerHTML='';
			self.dataEl.unbind('click');
			var data= $.evalJSON(o); 
			switch (type) {
				case 4:{
					self._createEconomic(data);
				}break;
				case 0:{
					if(!data["createDate"]){
						data["createDate"]=rtqDate;
					}
					self._createEarnings(data);
				}break;
				case 5:{
					self._createEvents(data);
				}break;
			}
			self._bindMoreEvent();
			self.changeOutSize();
			if (self.firstTag) {
				Util.DelayRun('onload', self.setIfreamOnFirst, 100, self);
			}
			self.hideLoading();
		});  
    },
    changeOutSize:function(w,h){
		var self=this,parent = this.el.parent().parent();
        var containerWidth = w || parent.width();
        h = h || parent.height();   
        var minWidth= this.staticValue.minWidth;
		if(this.profile.isAPI){
			if (isNaN(this.profile.width)) {
				containerWidth=Math.max(minWidth,containerWidth);
			}else{
				containerWidth=Math.max(this.profile.width,minWidth);
			}
		}
        h = h-this.staticValue.tabMenuHeight; 
		if (!this.profile.fixHeight) {
			this.el.css({
				width: containerWidth + "px"
			});
		}else {
			this.el.css({
				width: containerWidth + "px",
				height: h + "px"
			});
			if (this.dataScrollPN != null) {
				this.dataScrollPN.reSize(containerWidth,h);
			}
		}
    },
    _formatDate:function(date,type){
        var year=date.getFullYear(),
            month=(date.getMonth()+1)<10?"0"+(date.getMonth()+1):(date.getMonth()+1),
            day=date.getDate()<10?"0"+date.getDate():date.getDate(),
            dateStr=null;
        if(type=="yyyy-mm-dd"){
            dateStr=year+"-"+month+"-"+day;
        }
        return dateStr;
    },
	_formatDate2:function(str,format){
        if(str&&str!=null&&str.length!=0){
            var month=str.substring(5,7),
			year=str.substring(0,4),
            day=str.substring(8,10),
			time=str.substring(11,16);
            monthCodes={"01":"Jan","02":"Feb","03":"Mar","04":"Apr","05":"May","06":"Jun",
            "07":"Jul","08":"Aug","09":"Sep","10":"Oct","11":"Nov","12":"Dec"};
            if(format=='engMonth'){
                return monthCodes[month]+" "+day;
            }if(format=="mm-dd-yyyy"){
                return month+"-"+day+"-"+str.substring(0,4);
            }if(format=="date"){
				return day+"-"+monthCodes[month]+"-"+year;
			}if(format=="time"){
				return time+" ET";
			}
            return day+" "+monthCodes[month];
        }
        return '--';
    },
	openCalendars:function(sorceid){
        //baseURI
		if(this.profile.isAPI){
			api_common_openwindow.openWindow(this._getCalendarsURL(sorceid),"Calendars");
		}else{
			var profile = getDefaultProfileByType("12");
			RtqDesktop.addModule($.extend(true,{},profile,{widget:
				{lastActiveTabId:this.currentTab==null?this.lastActiveTabId:this.currentTab.id}
			}));
		}
    },
	_createEarnings:function(data){
		$(this._createBodyHtml(this.homePageHeadInfo["0"],data["earnings"],data)+this._createCopyRightHtml("zacks")).appendTo(this.dataEl);
	},
	_createEvents:function(data){
		$(this._createBodyHtml(this.homePageHeadInfo["5"],data["events"])+this._createCopyRightHtml("briefing")).appendTo(this.dataEl);
	},
    _createEconomic:function(data){
        $(this._createBodyHtml(this.homePageHeadInfo["4"],data["economic"])+this._createCopyRightHtml("briefing")).appendTo(this.dataEl);
        var self=this;
        this.dataEl.bind('click.Economic',function(e){
            var target=$(e.target);
			if(!target.hasClass('econ_cal_link')) return;
            var resourceId=target.attr('resourceId'),til=target.text();
			if(self.profile.isAPI){
				if (typeof self.callback.onClick == 'function') {
					self.callback.onClick({
						component: "homepagecalendars",
						url: self._getCalendarsURL(resourceId)
					});
				}
				else {
					self.openCalendars(resourceId);
				}
			}else{
				var postData={};
				postData["pTeam"]='NT';
				postData["tpl"]='Generic';
				postData["rId"]=resourceId;
				GB_NewsDataManager.getNewsContent(postData, function(o){
					if (o == null || o == '') {
						return;
					}
					var list = eval("(" + o + ")");
					var tl = (til == null ? "" : til), ct = (list.content == null ? "" : list.content), str = '<div><div class="content-bd">' + ct + '</div><div class="rtn-content-ft"><img src="IM/logo_briefing.png" height="38px"/><span>Copyright @ 2012 Briefing.com, Inc. All rights reserved.</span></div></div>';
					if (typeof workspaceManager != 'undefined') {
						workspaceManager.openNewsDetailWin(tl, str);
					}
				});
            }
        });
    },
	_getCalendarsURL:function(sorceid){
        var urlCfg=api_common_openwindow.getLocationArg();
        var data={};
        for(var attr in urlCfg){
            if(attr!='proxyurl'&&attr!='type'&&attr!='width'&&attr!='height'&&attr!="fixHeight"&&attr.indexOf("on")==-1){
                data[attr]=urlCfg[attr];
            }
        }
        data["tabID"]=this.currentTab==null?this.lastActiveTabId:this.currentTab.id;
		if (typeof sorceid != 'undefined' && $.trim(sorceid) != "") {
			data["currentID"]=sorceid;
		}
		return api_common_openwindow.genURL(data);
    },
	setIfreamOnFirst:function(){
        if(typeof this.callback.onLoad=='function'){
            this.callback.onLoad({
                component: "homepagecalendars",
                height: this.el.height(),
                minWidth : this.staticValue.minWidth
            });
            this.firstTag = false;
        }
    },
	_createBodyHtml:function(view,data,root){
		var viewConfig=view||[],html='<div class="rtq_table_wrap">',row=null,value=null,dataindex=null,dataFormat=null,subLen=null,
		render=null,flag=false,bodyData=data||[],len=bodyData.length;
		for (var i = 0; i < len; i++) {
			if (i < this.profile.top) {
				for (var j = 0, k = view.length; j < k; j++) {//row
					row = view[j];
					html += '<div class="'+(row.className||"")+'">';
					for (var h = 0, p = row.col.length; h < p; h++)//col
					{
						if (row.col[h].header) {
							value = row.col[h].header;
						}
						else {
							dataindex=row.col[h].dataIndex,subLen=row.col[h].subLen,dataFormat=row.col[h].dataFormat;
							render=row.col[h].renderer,flag=row.col[h].root;
							if(flag){
								value = root[dataindex]||"--";
							}else{
								value = bodyData[i][dataindex]||"--";
							}
							if (dataFormat) {
								value = this._formatDate2(value, dataFormat);
							}
							if(subLen){
								value=value.substr(0,subLen)+"...";
							}
							if(render){
								value=render(value,bodyData[i]);
							}
						}
						html += '<div class="qs-calendars-cell '+(row.col[h].className||"")+'">'+value+'</div>'
					}
					html+='</div>';
				}
			}else{
				if (this.showMore) {
					html += '<div class="qs-calendars-more clearfix"><div class="qs-calendars-cell">' + this.viewMoreText + '</div></div>';
				}
				break;
			}
        }
		if(len==0){
			html+="<div>No data available.</div>";
		}
		html+='</div>';
        return html;
	},
    _createCopyRightHtml:function(type){
        var html='';
        if (type == "briefing") {
            html='<div class="reproduction copyright"><div class="briefingLogo"></div><div class="rightContent"><span>Copyright &copy; 2012 Briefing.com, Inc.</span><br \><span> All rights reserved.</span></div></div>';
        }
        if(type=='zacks'){
            html='<div class="zacksCopyRight">'+
                 '<div><a target="_blank" href="http://news.morningstar.com/BriefNet/EarningsCal_popup.html">Earnings Release Date Data</a> Provided by <a target="_blank" href="http://www.zacks.com">ZACKS Investment Research, Inc.</a><br/>'+
                 '* The expected earnings release date for this firm has been estimated by ZACKS, based upon the company\'s historical report dates.'+
                 '</div></div>';
        }
        return html;
    },
	saveConfig:function(){
        return {
            lastActiveTabId:this.currentTab.id,
            title: this.getTitle()//for terminal
        };      
    },
    clear:function(){
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    }   
});
